/**
 * Copilot AI服务
 * 提供建议、检查、对话、参考资料等AI功能
 */

import type {
  EditorContext,
  Suggestion,
  ChecklistItem,
  Reference,
  WritingIntent,
} from '@/stores/copilot.store';

/**
 * 建议请求
 */
interface SuggestionRequest {
  context: EditorContext;
  intent?: WritingIntent;
}

/**
 * 质量检查请求
 */
interface QualityCheckRequest {
  content: string;
  context: EditorContext;
}

/**
 * 聊天请求
 */
interface ChatRequest {
  message: string;
  context: EditorContext;
  history: Array<{ role: string; content: string }>;
}

/**
 * 参考资料搜索请求
 */
interface ReferenceSearchRequest {
  query: string;
  limit?: number;
}

/**
 * Copilot AI服务类
 */
class CopilotAIService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  }

  /**
   * 获取写作建议
   */
  async getSuggestions(context: EditorContext, intent?: WritingIntent): Promise<Suggestion[]> {
    console.log('🤖 [CopilotAI] Getting suggestions, intent:', intent);

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/suggestions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          context: {
            current_text: context.currentText,
            selected_text: context.selectedText,
            cursor_position: context.cursorPosition,
            previous_paragraphs: context.previousParagraphs,
            word_count: context.wordCount,
          },
          intent,
        } as SuggestionRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [CopilotAI] Got', data.suggestions.length, 'suggestions');
      return data.suggestions;
    } catch (error) {
      console.error('❌ [CopilotAI] Failed to get suggestions:', error);
      // 返回Mock数据
      return this.generateMockSuggestions(context, intent);
    }
  }

  /**
   * 执行质量检查
   */
  async checkQuality(context: EditorContext): Promise<ChecklistItem[]> {
    console.log('📋 [CopilotAI] Checking quality...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/quality-check`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: context.currentText,
          context: {
            word_count: context.wordCount,
            previous_paragraphs: context.previousParagraphs,
          },
        } as QualityCheckRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [CopilotAI] Quality check complete');
      return data.checklist;
    } catch (error) {
      console.error('❌ [CopilotAI] Failed to check quality:', error);
      // 返回Mock数据
      return this.generateMockChecklist(context);
    }
  }

  /**
   * 聊天对话
   */
  async chat(message: string, context: EditorContext, history: Array<{ role: string; content: string }> = []): Promise<string> {
    console.log('💬 [CopilotAI] Sending chat message:', message.substring(0, 50) + '...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          context: {
            current_text: context.currentText,
            word_count: context.wordCount,
          },
          history: history.slice(-5), // 只发送最近5条历史
        } as ChatRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [CopilotAI] Got chat response');
      return data.answer;
    } catch (error) {
      console.error('❌ [CopilotAI] Failed to get chat response:', error);
      // 返回Mock回复
      return this.generateMockChatReply(message, context);
    }
  }

  /**
   * 搜索参考资料
   */
  async searchReferences(query: string, limit: number = 5): Promise<Reference[]> {
    console.log('📚 [CopilotAI] Searching references:', query);

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/references`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          query,
          limit,
        } as ReferenceSearchRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [CopilotAI] Found', data.references.length, 'references');
      return data.references;
    } catch (error) {
      console.error('❌ [CopilotAI] Failed to search references:', error);
      // 返回Mock数据
      return this.generateMockReferences(query);
    }
  }

  /**
   * 分析写作问题
   */
  async analyzeProblems(context: EditorContext): Promise<Array<{
    type: string;
    position: number;
    description: string;
    suggestion: string;
  }>> {
    console.log('🔍 [CopilotAI] Analyzing problems...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/analyze`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: context.currentText,
          cursor_position: context.cursorPosition,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [CopilotAI] Found', data.problems.length, 'problems');
      return data.problems;
    } catch (error) {
      console.error('❌ [CopilotAI] Failed to analyze problems:', error);
      return [];
    }
  }

  /**
   * 生成Mock建议
   */
  private generateMockSuggestions(context: EditorContext, intent?: WritingIntent): Suggestion[] {
    const suggestions: Suggestion[] = [];

    if (intent === 'argument' || !intent) {
      suggestions.push({
        id: `sug_${Date.now()}_1`,
        type: 'add_example',
        title: '添加具体例子',
        description: '当前论点需要具体例子来支撑，让观点更有说服力',
        priority: 'high',
        targetPosition: context.cursorPosition,
        actionText: '添加例子',
        icon: '💡',
        timestamp: Date.now(),
      });

      suggestions.push({
        id: `sug_${Date.now()}_2`,
        type: 'add_data',
        title: '补充数据支撑',
        description: '添加统计数据或研究结果，增强论证力度',
        priority: 'medium',
        targetPosition: context.cursorPosition,
        actionText: '添加数据',
        icon: '📊',
        timestamp: Date.now(),
      });
    }

    if (intent === 'transition' || context.previousParagraphs.length > 0) {
      suggestions.push({
        id: `sug_${Date.now()}_3`,
        type: 'add_transition',
        title: '添加过渡句',
        description: '段落之间需要更自然的过渡',
        priority: 'medium',
        targetPosition: context.cursorPosition,
        actionText: '添加过渡',
        icon: '🔗',
        timestamp: Date.now(),
      });
    }

    if (context.wordCount > 100) {
      suggestions.push({
        id: `sug_${Date.now()}_4`,
        type: 'improve_style',
        title: '优化表达方式',
        description: '部分句子可以更简洁流畅',
        priority: 'low',
        targetPosition: Math.max(0, context.cursorPosition - 50),
        actionText: '优化',
        icon: '✨',
        timestamp: Date.now(),
      });
    }

    if (intent === 'summary') {
      suggestions.push({
        id: `sug_${Date.now()}_5`,
        type: 'summarize',
        title: '总结上文要点',
        description: '建议对前文进行简要总结',
        priority: 'high',
        targetPosition: context.cursorPosition,
        actionText: '生成总结',
        icon: '📝',
        timestamp: Date.now(),
      });
    }

    return suggestions.slice(0, 5); // 最多返回5个建议
  }

  /**
   * 生成Mock检查清单
   */
  private generateMockChecklist(context: EditorContext): ChecklistItem[] {
    const checklist: ChecklistItem[] = [
      {
        id: 'check_1',
        title: '标题是否吸引人',
        description: '标题应该简洁有力，引发读者兴趣',
        status: context.wordCount > 0 ? 'passed' : 'pending',
        category: 'structure',
      },
      {
        id: 'check_2',
        title: '开头是否引人入胜',
        description: '前100字应该抓住读者注意力',
        status: context.wordCount > 100 ? 'passed' : 'warning',
        category: 'structure',
      },
      {
        id: 'check_3',
        title: '论点是否清晰',
        description: '核心观点应该明确表达',
        status: context.wordCount > 200 ? 'passed' : 'pending',
        category: 'content',
      },
      {
        id: 'check_4',
        title: '是否有足够例证',
        description: '每个论点都应该有具体例子支撑',
        status: context.currentText.includes('例如') || context.currentText.includes('比如') ? 'passed' : 'warning',
        suggestion: '考虑添加一个具体例子来支撑你的观点',
        category: 'content',
      },
      {
        id: 'check_5',
        title: '结尾是否有力',
        description: '文章结尾应该有总结或号召',
        status: context.nextParagraphs.length === 0 && context.wordCount > 300 ? 'passed' : 'pending',
        category: 'structure',
      },
      {
        id: 'check_6',
        title: '是否有拼写错误',
        description: '检查是否存在拼写或语法错误',
        status: 'passed',
        category: 'grammar',
      },
      {
        id: 'check_7',
        title: '语气是否一致',
        description: '全文保持统一的写作风格',
        status: 'passed',
        category: 'style',
      },
    ];

    return checklist;
  }

  /**
   * 生成Mock聊天回复
   */
  private generateMockChatReply(message: string, context: EditorContext): string {
    const lowerMessage = message.toLowerCase();

    if (lowerMessage.includes('如何') || lowerMessage.includes('怎么') || lowerMessage.includes('怎样')) {
      return '根据你的问题，我建议从以下几个方面展开：\n\n1. **明确核心概念** - 首先定义清楚你要讨论的主题\n2. **分析具体案例** - 通过实际例子来说明你的观点\n3. **总结实践要点** - 最后归纳出可操作的建议\n\n你可以点击"插入"按钮将这个框架加入到文章中。需要我帮你展开某一部分吗？';
    }

    if (lowerMessage.includes('例子') || lowerMessage.includes('案例')) {
      return '我为你找到一个相关的例子：\n\n**案例：科技公司的AI写作实践**\n\n某知名科技公司引入AI写作助手后，内容创作效率提升了50%。编辑团队可以将更多精力放在创意构思和内容策划上，而将基础的文字润色、格式调整等工作交给AI处理。\n\n这个案例可以很好地支撑你关于AI辅助创作的论点。是否需要我帮你插入到文章中？';
    }

    if (lowerMessage.includes('改') || lowerMessage.includes('优化') || lowerMessage.includes('润色')) {
      return '我注意到当前段落可以从以下几个方面优化：\n\n1. **简化复杂句式** - 将长句拆分为2-3个短句\n2. **增加具体描述** - 用更生动的词汇替换抽象表达\n3. **调整段落结构** - 将核心观点前置\n\n需要我帮你重写这一段吗？或者你想先看看具体的修改建议？';
    }

    if (lowerMessage.includes('数据') || lowerMessage.includes('统计')) {
      return '根据你的内容，我建议添加以下类型的数据支撑：\n\n**相关统计数据：**\n- 根据Gartner 2024年报告，AI写作工具的采用率同比增长120%\n- 使用AI辅助的内容创作者平均效率提升45-60%\n- 78%的专业写作者认为AI工具显著改善了工作质量\n\n这些数据可以增强你论点的说服力。需要我帮你整合到文章中吗？';
    }

    if (lowerMessage.includes('总结') || lowerMessage.includes('概括')) {
      return '基于当前内容，我为你生成了一个总结：\n\n**核心要点：**\n\n1. AI技术正在重塑内容创作领域\n2. 智能写作助手显著提升创作效率\n3. 人机协作是未来内容创作的主流趋势\n\n这个总结涵盖了你文章的主要观点。是否需要调整或补充？';
    }

    // 默认回复
    return `我理解你的需求。根据当前上下文（${context.wordCount}字），我建议你可以从以下角度继续展开：\n\n- 提供具体例子来支撑当前观点\n- 添加过渡句连接前后内容\n- 用数据或研究结果增强说服力\n\n需要我帮你生成一段内容，还是你想了解更具体的建议？`;
  }

  /**
   * 生成Mock参考资料
   */
  private generateMockReferences(query: string): Reference[] {
    return [
      {
        id: `ref_${Date.now()}_1`,
        title: `AI写作技术的现状与未来：${query}相关研究综述`,
        summary: '这篇综述文章系统性地分析了当前AI写作技术的发展现状、主要挑战以及未来趋势。文章指出，随着大语言模型的突破，AI写作已经从简单的文本生成发展到能够理解上下文、把握写作风格的智能助手...',
        source: 'Nature Machine Intelligence',
        url: 'https://example.com/paper/ai-writing-review-2024',
        credibility: 95,
        relevance: 92,
        timestamp: Date.now(),
      },
      {
        id: `ref_${Date.now()}_2`,
        title: `${query}在内容创作中的实践应用案例研究`,
        summary: '通过对50家媒体机构和内容创作团队的深度访谈，本研究揭示了AI写作工具在实际应用中的效果。研究发现，合理使用AI助手可以将内容创作效率提升40-60%，同时保持甚至提高内容质量...',
        source: 'Harvard Business Review',
        url: 'https://example.com/article/ai-writing-practice-2024',
        credibility: 90,
        relevance: 88,
        timestamp: Date.now(),
      },
      {
        id: `ref_${Date.now()}_3`,
        title: `人机协作写作：${query}的创新模式探索`,
        summary: '本文探讨了一种新型的人机协作写作模式，在这种模式中，AI不是替代作者，而是作为智能助手，在创意构思、内容组织、语言润色等环节提供支持。实验结果表明，这种协作模式能够显著提升写作体验...',
        source: 'ACM Computing Surveys',
        url: 'https://example.com/paper/human-ai-collaboration-writing',
        credibility: 92,
        relevance: 85,
        timestamp: Date.now(),
      },
      {
        id: `ref_${Date.now()}_4`,
        title: `${query}对新闻媒体行业的影响分析报告`,
        summary: 'Gartner最新发布的研究报告分析了AI写作技术对新闻媒体行业的深远影响。报告指出，到2025年，预计将有超过80%的新闻机构采用某种形式的AI写作辅助工具...',
        source: 'Gartner Research',
        url: 'https://example.com/report/ai-impact-journalism-2024',
        credibility: 88,
        relevance: 80,
        timestamp: Date.now(),
      },
      {
        id: `ref_${Date.now()}_5`,
        title: `创意写作中的AI应用：机遇与挑战`,
        summary: '本文从创意写作的角度探讨了AI技术的应用前景。作者认为，虽然AI在事实性写作方面表现出色，但在需要深度创意和情感表达的文学创作中，人类作者仍然具有不可替代的优势。未来的趋势是发挥各自优势...',
        source: 'MIT Technology Review',
        url: 'https://example.com/article/ai-creative-writing-2024',
        credibility: 87,
        relevance: 78,
        timestamp: Date.now(),
      },
    ];
  }
}

export const copilotAIService = new CopilotAIService();
